public class Solution {
    public boolean isBalanced(TreeNode root) {
        return dfsHeight(root) != -1;
    }

    public int dfsHeight(TreeNode root) {
        if (root == null) {
            return 0; // 空树高度为0
        }
        int leftHeight = dfsHeight(root.left);
        if (leftHeight == -1) {
            return -1; // 左子树不平衡
        }
        int rightHeight = dfsHeight(root.right);
        if (rightHeight == -1) {
            return -1; // 右子树不平衡
        }
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1; // 当前节点不平衡
        }
        return Math.max(leftHeight, rightHeight) + 1; // 返回当前节点的高度
    }

    // TreeNode 类定义
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        TreeNode root1 = new TreeNode(3);
        root1.left = new TreeNode(9);
        root1.right = new TreeNode(20);
        root1.right.left = new TreeNode(15);
        root1.right.right = new TreeNode(7);
        System.out.println("Is Balanced: " + solution.isBalanced(root1)); // 输出：true
    }
}